const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const request = {
  get: function (url, queryParams) {
    return this._request(url, 'GET', queryParams)
  },
  post: function (url, data) {
    return this._request(url, 'POST', data)
  },
  delete: function (url) {
    return this._request(url, 'DELETE')
  },
  put: function (url, data) {
    return this._request(url, 'PUT', data);
  },
  // 自己用，先简单写，不做容错
  _request(url, method, data) {
    const domain = 'https://www.jsmzr.top';
    url = domain + url;
    if (method != 'GET') {
      url = this._setRequestCsrf(url);
    }
    const _resolveResponseCsrf = this._resolveResponseCsrf;
    const header = this._getHeader();
    return new Promise((resolve, reject) => wx.request({
      url,
      data,
      method,
      header,
      success(res){
        if (res.statusCode != 200) {
          reject(Error('response code:' + res.statusCode))
        } else {
          _resolveResponseCsrf(res);
          resolve(res.data)
        }
      },
      fail(res) {
        console.log(res)
      }
    }));
  },
  _getHeader() {
    const cookies = [];
    const session = wx.getStorageSync('EGG_SESS');
    const csrf = wx.getStorageSync('csrfToken');
    if (session) {
      cookies.push('EGG_SESS=' + session);
    }
    if (csrf) {
      cookies.push('csrfToken=' + csrf);
    }
    return {
      cookie: cookies.join(';')
    };
  },
  _setRequestCsrf (url) {
    const csrf = wx.getStorageSync('csrfToken');
    if (!csrf) return url;
    const last = url.lastIndexOf('?');
    url += (last < 0 ? '?' : last == url.length - 1 ? '' : '&') + '_csrf=' + csrf;
    return url;
  },
  _resolveResponseCsrf (res) {
    let cookies = res.cookies;
    console.log('cookies', cookies);
    console.log('header', res.header);
    let session;
    let csrf;
    if (!cookies) {
      const cookieStr = res.header['Set-Cookie'];
      if (!cookieStr) return;
      const tmp = cookieStr.split(';').filter(o => o.includes('EGG_SESS') || o.includes('csrfToken'));
      session = tmp.filter(o => o.includes('EGG_SESS')).map(o => o.substring(o.indexOf('EGG_SESS=')).split('=')[1]);
      csrf = tmp.filter(o => o.includes('csrfToken')).map(o => o.substring(o.indexOf('csrfToken=')).split('=')[1]);
    } else {
      session = cookies.filter(o => o.startsWith('EGG_SESS')).map(oo => oo.split(';')[0].split('=')[1]);
      csrf = cookies.filter(o => o.startsWith('csrfToken')).map(oo => oo.split(';')[0].split('=')[1]);
    }
    if (session.length > 0) {
      console.log('set session', session[0]);
      wx.setStorageSync('EGG_SESS', session[0]);
    }
    if (csrf.length > 0) {
      console.log('set csrfToken', csrf[0]);
      wx.setStorageSync('csrfToken', csrf[0]);
    }
  },
  _resolveIosCookie (res) {
    const header = res.header;
    const cookieStr = header['Set-Cookie'];
    if (!cookieStr) return;
    const cookies = cookieStr.split(';');
    const session = cookies.filter(o=>o.startsWith('EGG_SESS')).map(oo => oo.split('=')[1]);
    if (session.length > 0) {
      wx.setStorageSync('EGG_SESS', session[0]);
    }
    const csrf = cookies.filter(o=>o.startsWith('csrfToken')).map(oo => oo.split('=')[1]);
    if (csrf.length > 0) {
      wx.setStorageSync('csrfToken', session[0]);
    }
  }
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime,
  request,
}
